package com.gcloud.mesh.dcs.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.mvel2.MVEL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.CloudResourceDao;
import com.gcloud.mesh.asset.entity.CloudResourceEntity;
import com.gcloud.mesh.dcs.dao.AppDao;
import com.gcloud.mesh.dcs.entity.AppEntity;
import com.gcloud.mesh.dcs.enums.DeviceThresholdType;
import com.gcloud.mesh.dcs.strategy.huawei.BatchListMetricDataSolution;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.gcloud.mesh.supplier.dao.SupplierDao;
import com.gcloud.mesh.supplier.entity.SupplierEntity;
import com.huaweicloud.sdk.ces.v1.model.BatchListMetricDataResponse;
import com.huaweicloud.sdk.ces.v1.model.BatchMetricData;

import lombok.extern.slf4j.Slf4j;

/**
 * 阿里ecs 内存 计算
 */
@Component
@Slf4j
public class HuaweiMemSpaceThreholdService implements IDeviceThresholdService {

    @Autowired
    private SupplierDao supplierDao;
    @Autowired
    private CloudResourceDao cloudResourceDao;
    @Autowired
    private AppDao appDao;


    @Override
    public DeviceThresholdType device() {
        return DeviceThresholdType.HUAWEI_MEM_SPACE;
    }

    private Double getEcsMemValue(String accessKeyId, String secret, String regionId, String instanceId){
    	BatchListMetricDataSolution listMetric = new BatchListMetricDataSolution();
    	long from = System.currentTimeMillis()-600000;//60秒钟检查一次
    	long to = System.currentTimeMillis();
    	BatchListMetricDataResponse res = listMetric.listMetricData(instanceId, regionId, accessKeyId, secret, from, to);
    	log.debug("======获取华为云服务器:"+instanceId+"监控数据返回"+res.toString());
    	List<BatchMetricData>  datas = res.getMetrics();
    	if(res.getMetrics() != null) {
    		for(BatchMetricData data : datas) {
    			if("mem_usedPercent".equals(data.getMetricName())) {
    				if(data.getDatapoints()!= null && !data.getDatapoints().isEmpty()) {
    					// log.info("监控项[HUAWEI_MEM_UTIL] menVal: {}",data.getDatapoints().get(0).getAverage());
    					return data.getDatapoints().get(0).getAverage();
    				}
    			}
    		}
    	}
    	return 0.0;
    }

 
    public Boolean checkScheduler(String appId, String operation, Double value) {
        // 获取ecs 服务器监控数据
    	AppEntity appEntity = appDao.getById(appId);
        if(appEntity==null) return false;
        CloudResourceEntity cloudResourceEntity = cloudResourceDao.findOneByProperty("id", appEntity.getCloudResourceId());
        if(cloudResourceEntity==null) return false;
        // String configValue = supplierDao.getConfigValueByDatacenterId(SystemType.ALI.getName(),cloudResourceEntity.getDatacenterId());
    	SupplierEntity supplierEntity = supplierDao.findOneByProperty("datacenterId", cloudResourceEntity.getDatacenterId());
        HuaweiMigrationParam huaweiMigrationParam = JSONObject.toJavaObject(JSONObject.parseObject(supplierEntity.getConfig()), HuaweiMigrationParam.class);
        if(huaweiMigrationParam == null || StringUtils.isBlank(huaweiMigrationParam.getAccessKey())) return false;
        Double memVal = getEcsMemValue(huaweiMigrationParam.getAccessKey(), huaweiMigrationParam.getSecretKey(), huaweiMigrationParam.getRegionId(), appId);
        String evalExpression = String.format("memVal %s reqVal",operation);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("memVal",memVal);
        paramMap.put("reqVal",value);
        Boolean aBoolean = MVEL.evalToBoolean(evalExpression, paramMap);
        log.info("监控项[HUAWEI_MEM_UTIL] id:{}, memVal:{},reqVal:{},evalExpression:{},result:{}", cloudResourceEntity.getDatacenterId(), memVal,value,evalExpression,aBoolean);
        return aBoolean;
    }
}
